<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="资产名称" prop="assetId">
        <el-select v-model="queryParams.assetId" placeholder="请选择资产名称" clearable>
          <el-option
            v-for="asset in assetList"
            :key="asset.assetId"
            :label="asset.assetName"
            :value="asset.assetId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分配人员" prop="assignedPersonnel">
        <el-select v-model="queryParams.assignedPersonnel" filterable placeholder="请选择分配人员" clearable>
          <el-option
            v-for="dict in personList"
            :key="dict.userId"
            :label="dict.nickName"
            :value="dict.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预计上门时间" prop="onsiteTime">
        <el-date-picker clearable
                        style="width: 205px"
                        v-model="queryParams.onsiteTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择预计上门时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="紧急程度" prop="urgencyLevel">
        <el-select v-model="queryParams.urgencyLevel" placeholder="请选择紧急程度" clearable>
          <el-option
            v-for="dict in dict.type.work_order_emergency_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="工单状态" prop="workOrderStatus">
        <el-select v-model="queryParams.workOrderStatus" placeholder="请选择工单状态" clearable>
          <el-option
            v-for="dict in dict.type.work_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange" @row-click="handleRowClick">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="资产编号" width="140" align="center" prop="assetNumber" >
      </el-table-column>
      <el-table-column label="资产名称" width="280px" show-overflow-tooltip align="center" prop="assetId" >
        <template slot-scope="scope">
          {{scope.row.assetId | assetName(assetList, scope.row.assetId)}}
        </template>
      </el-table-column>
      <el-table-column label="分配人员" align="center" prop="assignedPersonnel" >
        <template slot-scope="scope">
          {{scope.row.assignedPersonnel | personName(personList, scope.row.assignedPersonnel)}}
        </template>
      </el-table-column>
      <el-table-column label="派单时间" align="center" prop="dispatchTime" />
      <el-table-column label="紧急程度" align="center" prop="urgencyLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.work_order_emergency_type" :value="scope.row.urgencyLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="工单状态" align="center" prop="workOrderStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.work_order_status" :value="scope.row.workOrderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="发现问题"  show-overflow-tooltip align="center" prop="problemDescription">

      </el-table-column>
      <el-table-column label="严重程度" align="center" prop="severityLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_severity_level" :value="scope.row.severityLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="primary"
            title="修改"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
          ></el-button>
          <el-button
            size="small"
            type="danger"
            title="删除"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改保养维护工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="资产名称" prop="assetId">
              <el-select v-model="form.assetId" filterable @change="changeAsset" style="width: 100%" clearable placeholder="请选择资产名称">
                <el-option
                  v-for="asset in assetList"
                  :key="asset.assetId"
                  :label="asset.assetName"
                  :value="asset.assetId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="紧急程度" prop="urgencyLevel">
              <el-select v-model="form.urgencyLevel" style="width: 100%" clearable placeholder="请选择紧急程度">
                <el-option
                  v-for="dict in dict.type.work_order_emergency_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分配人员" prop="assignedPersonnel">
              <el-select v-model="form.assignedPersonnel" style="width: 100%" clearable placeholder="请选择分配人员">
                <el-option
                  v-for="dict in personList"
                  :key="dict.userId"
                  :label="dict.nickName"
                  :value="dict.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>


          <el-col :span="8">
            <el-form-item label="预计上门时间" prop="onsiteTime">
              <el-date-picker clearable style="width: 100%"
                v-model="form.onsiteTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择预计上门时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="现场联系人" prop="onsiteContact">
              <el-input v-model="form.onsiteContact" placeholder="请输入现场联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="form.contactNumber" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="form.notes" rows="3" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="图片" prop="images">
          <image-upload :limit="10" v-model="form.images"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listOrder, getOrder, delOrder, addOrder, updateOrder, getOrderWorker} from "@/api/business/order";
import {getAssetInfoList} from "@/api/business/assetInfo";

export default {
  name: "Order",
  dicts: ['work_order_method', 'work_order_emergency_type', 'work_order_type', 'work_order_status', 'order_severity_level'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 保养维护工单表格数据
      orderList: [],
      assetList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workOrderType: 1,
        assetId: null,
        urgencyLevel: null,
        workOrderMethod: null,
        assignedPersonnel: null,
        onsiteTime: null,
        onsiteContact: null,
        contactNumber: null,
        workImage: null,
        createdAt: null,
        updatedAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        assetId: [
          { required: true, message: "请选择资产", trigger: "change" }
        ],
        urgencyLevel: [
          { required: true, message: "请选择紧急程度", trigger: "change" }
        ],
        assignedPersonnel: [
          { required: true, message: "请选择分配人员", trigger: "change" }
        ],
        onsiteTime: [
          { required: true, message: "预计上门时间不能为空", trigger: "change" }
        ],
      },
      personList: []
    };
  },
  created() {
    this.getOrderWorker()
    this.getInfoData()
    this.getList();
  },
  filters: {
    assetName: (value, list) => {
      let item = list.find(item => item.assetId == value)
      return item ? item.assetName : ''
    },
    assetId: (value, list) => {
      let item = list.find(item => item.assetId == value)
      return item && item.assetNumAttached ? `${item.assetNumMaster}-${item.assetNumAttached}` : `${item.assetNumMaster}`
    },
    personName: (value, list) => {
      let item = list.find(item => item.value == value)
      return item? item.label : ''
    }
  },
  methods: {
    getOrderWorker() {
      getOrderWorker().then(r => {
        this.personList = r
      })
    },
    getInfoData() {
      getAssetInfoList().then(r => {
        this.assetList = r.data
      })
    },
    changeAsset(val) {
      if(val) {
        let item = this.assetList.find(item => item.assetId == val)
        let number = ''
        if(item.assetNumAttached) {
          number = item.assetNumMaster + '-' + item.assetNumAttached
        } else {
          number = item.assetNumMaster
        }
        this.form.assetNumber = number
      } else {
        this.form.assetNumber = ''
      }
    },
    /** 查询保养维护工单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        assetId: null,
        assetNumber: null,
        urgencyLevel: null,
        workOrderMethod: null,
        workOrderType: 1,
        workOrderCategory: null,
        workOrderStatus: null,
        problemDescription: null,
        severityLevel: null,
        assignedPersonnel: null,
        dispatchTime: null,
        onsiteTime: null,
        onsiteContact: null,
        contactNumber: null,
        notes: null,
        images: null,
        createdAt: null,
        updatedAt: null,
        delFlag: null,
        deptId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 行点击
    handleRowClick(row, column, event) {
      if(column.label != '操作') {
        this.$router.push('/OrderLedger/inspection-info/' + row.id)
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加巡检工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改巡检工单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除巡检工单编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
